<template>
  <div class="loading">
    <van-loading type="spinner" size="35px" color="#1989fa" vertical>{{
      title
    }}</van-loading>
  </div>
</template>

<script>
const config = require("../../../config");
import { getUserInfo } from "@/api/user";
// 判断是否为公众号模拟器环境
const isWechat = () => {
  return (
    String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) ===
    "micromessenger"
  );
};
// 判断公众号截取code
const getUrlParam = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let r = window.location.search.slice(1).match(reg);
  if (r != null) {
    return decodeURIComponent(r[2]);
  }
  return null;
};
export default {
  name: "App",
  data() {
    return {
      code: "",
      title: "加载中...",
    };
  },
  created() {},
  mounted() {
    this.getWxCode();
  },
  methods: {
    getWxCode() {
      //微信环境
      if (isWechat()) {
        const callbackURL = encodeURIComponent(
          "https://clywlsq.gongshu.gov.cn/wxy_cly/"
        ); // 回调页面window.location.href
        const appid = config.appid; //公众号 appid
        let code = getUrlParam("code"); //是否存在code
        if (code == null || code === "") {
          //不存在就打开上面的地址进行授权
          let redirectURI = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${callbackURL}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`; //每个字段对应什么意思 微信文档可以查询
          window.location.href = redirectURI;
        } else {
          this.code = code;
          this.loadUserInfo();
        }
        //非微信环境
      } else {
        this.title = "请在微信中打开...";
      }
    },
    loadUserInfo() {
      getUserInfo({
        authCode: this.code,
        appName: config.appAbbr,
      }).then((res) => {
        this.$store.commit("user/setLoginData", res.data);
        this.$router.push("/home");
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.loading {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
